import { createRouter, createWebHistory } from 'vue-router'

// 定义路由
const routes = [
  {
    path: '/',
    name: 'Home',
    // 懒加载组件
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/article',
    name: 'ArticleList',
    component: () => import('../views/article/ArticleList.vue'),
    meta: {
      title: '文章列表'
    }
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('../views/article/ArticleDetail.vue'),
    meta: {
      title: '文章详情'
    }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: {
      title: '管理后台',
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: {
      title: '注册'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 设置页面标题和登录验证
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - Wave Blog'
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    // 检查是否已登录
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      next()
    } else {
      // 未登录，跳转到登录页
      next('/login')
    }
  } else {
    next()
  }
})

export default router